package com.lyc.utils;

import org.springframework.util.DigestUtils;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author YooLin
 * @Date 2017/8/17 22:47
 * @Description
 * 改善：加盐
 */
public class MD5Util {
    /**
     * 加密密码
     * @param password 待加密的密码
     * @param username
     * @return 加密后的密码
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String encryptPassword(String password, String username) throws NoSuchAlgorithmException, UnsupportedEncodingException {
//        MessageDigest md5 = MessageDigest.getInstance("MD5");
//        //使用Base64是为了防止md5加密出现乱码问题
//        BASE64Encoder base64Encoder = new BASE64Encoder();
//        String result = base64Encoder.encode(md5.digest(password.getBytes("utf-8")));
        String base = username+password;
        return DigestUtils.md5DigestAsHex(base.getBytes());
    }

    /**
     * 校验密码
     * @param inputPwd 用户输入的密码
     * @param dbPwd 查找数据库的密码
     * @return true 校验成功 false 校验失败
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static boolean checkPassword(String inputPwd,String username, String dbPwd) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return encryptPassword(inputPwd,username).equals(dbPwd);
    }
}
